import { useRequest } from "@/hooks/useRequest";
import { REQUEST_LOGIN } from "@/api/user";

import { LoginParams, LoginStatus, LoginStatusEnum, UserState } from "./types";

export const actions = {
	async login(this: UserState, params: LoginParams, cb: (e: LoginStatus) => void): Promise<void> {
		const { onSubmitRequest } = useRequest<any, LoginParams>(REQUEST_LOGIN);

		onSubmitRequest(
			{
				onSuccess: async res => {
					this.token = res.token;

					cb &&
						cb({
							status: LoginStatusEnum.SUCCESS,
							loading: false
						});
				},
				onError: (error) => {
					cb &&
						cb({
							status: LoginStatusEnum.ERROR,
							message: error.message,
							loading: false
						});
				},
			},
			params
		);
	},
};
